package br.com.rapidrest.chain;

import java.lang.reflect.Method;

import br.com.rapidrest.exception.ChainException;
import br.com.rapidrest.exception.RequestException;
import br.com.rapidrest.request.RequestScope;
import br.com.rapidrest.util.MethodUtil;

public class MethodFinderCommand implements Command {

	public static final String DEFAULT_INIT_METHOD = "init";

	@Override
	public void execute(Chain chain) throws ChainException {
		BasicChainContext context = (BasicChainContext) chain.getContext();
		RequestScope requestScope = context.getRequestScope();
		
		Class<?> beanClass = requestScope.getBeanClass();
		
		String methodName = requestScope.getMethodName();
		if (methodName == null) {
			methodName = DEFAULT_INIT_METHOD;
		}

		int paramsSize = 0;
		String[] params = requestScope.getParams();
		if (params != null) {
			paramsSize = params.length;
		}

		Method method = MethodUtil
				.findMethod(beanClass, methodName, paramsSize);
		// init method is optional!
		if (method == null && !methodName.equals(DEFAULT_INIT_METHOD)) {
			throw new RequestException("Method " + beanClass.getName() + "."
					+ methodName + " with " + paramsSize
					+ " parameters was not found.");
		}
		context.setMethod(method);

		chain.proceed();
	}

}
